package com.uzhie.spring;

import com.alibaba.fastjson.JSONObject;
import org.apache.log4j.Logger;
import org.springframework.http.MediaType;
import org.springframework.web.HttpRequestHandler;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.mvc.method.RequestMappingInfo;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;

/**
 * Created by TangFei on 2018/7/18.
 */
public class HttpHandler implements HttpRequestHandler {
    private Logger logger = Logger.getLogger(this.getClass());

    private Map<String, HttpClassMethod> classMethodMap;
    private RequestMappingHandlerMapping handlerMapping;

    public void setHandlerMapping(RequestMappingHandlerMapping handlerMapping) {
        logger.info(handlerMapping);
        Map<RequestMappingInfo, HandlerMethod> handlerMethods = handlerMapping.getHandlerMethods();
        for (Map.Entry<RequestMappingInfo, HandlerMethod> entry : handlerMethods.entrySet()) {
            logger.info(entry);
        }
        this.handlerMapping = handlerMapping;
    }

    public void setApplicationContextAware(HttpApplicationContextAware applicationContextAware) {
        setClassMethodMap(applicationContextAware);
    }

    private void setClassMethodMap(HttpApplicationContextAware applicationContextAware) {
        this.classMethodMap = applicationContextAware.getClassMethodMap();
    }

    @Override
    public void handleRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType(MediaType.APPLICATION_JSON_VALUE);
        response.setCharacterEncoding("UTF-8");
        JSONObject object = new JSONObject();
        object.put("account", "sadfasdf");
        response.getOutputStream().write(object.toJSONString().getBytes());
        response.getOutputStream().flush();
    }
}
